package com.mxl.datebase.orm.ibatis;

import java.sql.SQLException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.mxl.datebase.orm.BatchDao;


/**
 * 基于ibatis的大数据量的批量处理Support类.
 * 
 * @autho
 */
public class BatchDaoSupport extends SqlMapClientDaoSupport implements BatchDao {
	
	private Logger logger = LoggerFactory.getLogger(BatchDaoSupport.class);
	
	private interface Handler<T> {
		void handle(String statementName,T model)  throws SQLException;
	}
	
	protected <X> int batchExecute(Handler<X> handler,String statementName,List<X> list) throws SQLException {
		int tmp = 0;
		try {
			getSqlMapClient().startBatch();
			for (X model : list) {
				handler.handle(statementName,model);
			}
			tmp = getSqlMapClient().executeBatch();
		} catch (SQLException e) {
			logger.error("[" + statementName + "]" + " batch execute failed", e);
			throw e;
		}
		return tmp;
	}
	
	public <X> int batchUpdate(String statementName,List<X> list) throws SQLException {
		return batchExecute(new Handler<X>(){
			public void handle(String statementName, X model) throws SQLException{
				getSqlMapClient().update(statementName, model);
			}
		}, statementName, list);
	}
	
	public <X> int batchDelete(String statementName,List<X> list) throws SQLException {
		return batchExecute(new Handler<X>(){
			public void handle(String statementName, X model) throws SQLException{
				getSqlMapClient().delete(statementName, model);
			}
		}, statementName, list);
	}
	
	public <X> int batchInsert(String statementName,List<X> list) throws SQLException {
		return batchExecute(new Handler<X>(){
			public void handle(String statementName, X model) throws SQLException{
				getSqlMapClient().insert(statementName, model);
			}
		}, statementName, list);
	}
}